import subprocess
import time

googleAccount = "wk110@keyan.ai"
project_pre = "laibo01"
project_range = range(1, 2)  # 不包含右边
do_create_project = True


def create_project(project, do_create_project):
    if not do_create_project:
        return project
        # 创建项目
    while True:
        cmd_create = "gcloud projects create {}".format(project) + " --name=\"" + project + "\""
        (status, create_res) = subprocess.getstatusoutput(cmd_create)
        if "The project ID you specified is already in use by another project" in create_res:
            name, number = project.split("-", -1)
            project = name + "-" + str(int(number) + 1)
            print("create same name project , change name to {}".format(project))
        elif "The project cannot be created because you have exceeded your allotted project quota" in create_res:
            print("project number limit ,done process")
            exit(0)
        else:
            # todo 判断成功的条件
            print(create_res)
            return project


def set_project(project):
    #  指定项目
    cmd_set_project = "gcloud config set project " + project
    (status, set_project_res) = subprocess.getstatusoutput(cmd_set_project)
    if "ERROR" in set_project_res:
        print(set_project_res)
        exit(0)
    else:
        print("set project success")


def enable_api():
    # 开启api
    cmd_enable_api = "gcloud services enable drive.googleapis.com"
    (status, enable_api_res) = subprocess.getstatusoutput(cmd_enable_api)
    print(enable_api_res)
    if "ERROR" in enable_api_res:
        print(" enable compute engine Manual")
        exit(0)


if __name__ == '__main__':
    print("开始: {}".format(time.strftime("%Y-%m-%d %H-%M-%S", time.localtime())))
    for index in project_range:
        project = project_pre + "-" + str(index)
        project = create_project(project, do_create_project)
        set_project(project)
        enable_api()
        print("完成", project)
    print("完成操作")
